package com.cyz.springdemo.service;

import com.cyz.springdemo.model.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

/**
 * @program: springdemo
 * @description: Redis测试消费的服务类
 * 注意：系统启动之后，自动运行有两种方法：
 * 一、使用注解@PostConstruct,就可实现
 * 二、实现 InitializingBean 在afterPropertiesSet()里面调用方法，或者直接写在里面
 * @author: wangjie
 * @create: 2019-07-26 17:02
 **/

@Service
public class RedisTestService implements InitializingBean {

    private Logger logger = LoggerFactory.getLogger(RedisTestService.class);

    @Autowired
    private RedisTemplate<String, User> redisTemplate;

    //@PostConstruct          //随着项目启动而运行
    //public void customer(){
    //    while (true){
    //        User user = redisTemplate.opsForList().leftPop("my:list",10, TimeUnit.SECONDS);
    //        System.out.println(user);
    //    }
    //}

    @Override
    public void afterPropertiesSet() throws Exception {
        /*new Thread(() ->{
            while (true){
                *//**
                 * 如果不加try，在队列消费的时候如果报异常，则会跳出循环，不继续进行消费,用try之后会把异常抛出，不影响后续的消费
                 * 如果有队列则取出，没有的话进行10秒的阻塞
                 *//*
                try {
                    User user = redisTemplate.opsForList().leftPop("my:list", 10, TimeUnit.SECONDS);
                    if (user != null) {
                        // TODO业务逻辑处理
                        logger.info("{}",user);
                    }else {
                        logger.info("{}","已经消费完了");
                    }
                }catch (Exception e){
                    e.printStackTrace();
                    try {
                        TimeUnit.SECONDS.sleep(10);
                    } catch (InterruptedException e1) {
                        e1.printStackTrace();
                    }
                }
            }
        }).start();*/
    }
}
